package com.simplehire.repository;

import com.simplehire.model.InterviewResult;
import com.simplehire.model.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;

@Repository
public interface InterviewResultRepository extends JpaRepository<InterviewResult, Long> {

    /**
     * 根据用户查找面试结果
     */
    List<InterviewResult> findByUser(User user);

    /**
     * 根据用户ID查找面试结果（分页）
     */
    Page<InterviewResult> findByUserId(Long userId, Pageable pageable);

    /**
     * 根据用户查找面试结果（按创建时间倒序）
     */
    List<InterviewResult> findByUserOrderByCreatedAtDesc(User user);

    /**
     * 查找用户最近的面试结果
     */
    @Query("SELECT ir FROM InterviewResult ir WHERE ir.user = :user ORDER BY ir.createdAt DESC")
    List<InterviewResult> findRecentByUser(@Param("user") User user, Pageable pageable);

    /**
     * 根据分数范围查找面试结果
     */
    List<InterviewResult> findByScoreBetween(Integer minScore, Integer maxScore);

    /**
     * 查找指定时间范围内的面试结果
     */
    List<InterviewResult> findByCreatedAtBetween(LocalDateTime startDate, LocalDateTime endDate);

    /**
     * 根据用户ID查找面试结果（按创建时间倒序）
     */
    List<InterviewResult> findByUserIdOrderByCreatedAtDesc(Long userId);
    
    /**
     * 根据ID和用户ID查找面试结果
     */
    java.util.Optional<InterviewResult> findByIdAndUserId(Long id, Long userId);
    
    /**
     * 统计用户的面试次数
     */
    @Query("SELECT COUNT(ir) FROM InterviewResult ir WHERE ir.user = :user")
    Long countByUser(@Param("user") User user);

    /**
     * 计算用户的平均分数
     */
    @Query("SELECT AVG(ir.score) FROM InterviewResult ir WHERE ir.user = :user AND ir.score IS NOT NULL")
    Double getAverageScoreByUser(@Param("user") User user);

    /**
     * 查找用户的最高分数
     */
    @Query("SELECT MAX(ir.score) FROM InterviewResult ir WHERE ir.user = :user AND ir.score IS NOT NULL")
    Integer getMaxScoreByUser(@Param("user") User user);
}